<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="baseAddConfig" :questions="baseQuestions" ref="base" />
    </BaseCollapse>

    <BaseCollapse title="续借档案列表">
      <DynamicForm :config="renewalListAddConfig" :questions="renewalListAddQuestions" ref="renewalList" v-if="['ADD', 'UPDATE'].includes(state.showType)">
        <template #renewDuration="{ question }">
          <a-input-number v-model:value="question.renewDuration" placeholder="请输入" :min="0" :parser="numberRep" />
        </template>
      </DynamicForm>
      <DynamicTable :config="renewalListViewTableConfig" :tables="renewalListViewTable" v-if="['VIEW', 'AUDIT'].includes(state.showType)"></DynamicTable>
    </BaseCollapse>

    <!-- <BaseCollapse v-if="['AUDIT'].includes(state.showType)" title="审批意见">
      <DynamicForm :config="approvalOpinionsConfig" :questions="approvalOpinionsQuestions" ref="approvalOpinions" />
    </BaseCollapse> -->

    <ApprovalDetail v-if="['VIEW', 'AUDIT'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>

    <div class="space-x-2 w-full text-center my-4">
      <a-button v-if="state.showType !== 'AUDIT'" @click="goBack">返回</a-button>
      <a-button v-if="['ADD', 'UPDATE'].includes(state.showType)" @click="savePageInfo(0)">暂存</a-button>
      <a-button v-if="['ADD', 'UPDATE'].includes(state.showType)" type="primary" @click="savePageInfo(1)">提交</a-button>
      <a-button v-if="['CONFIRM'].includes(state.showType)" type="primary" @click="reviewSubmit">提交</a-button>
      <a-button v-if="['VIEW'].includes(state.showType) && [1, 3].includes(state.status)" type="primary" @click="toUpdate">编辑</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import ApprovalDetail from '@/components/approval-details/index.vue';
import AuditRecord from '@/components/common/AuditRecord/index.vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import {
  Api,
  archivesRenewInfoAudit,
  archivesRenewInfoSave,
  archivesBorrowFindBorrowFileByFileName,
  archivesBorrowFindFileListByBorrowInfoIds,
  archivesRenewInfoRenewFilesPage
} from '@/config/api/archivesRenew';
import { Api as searchManageApi, advancedQueryPreview } from '@/config/api/searchManage';
import { Api as archivesBorrowApi } from '@/config/api/archivesBorrow';
import { Modal, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { filter } from 'rxjs/operators';
import { getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import indexService from './index.service';
import { HOST } from '@/config';
import { useUserStoreWithOut } from '@/store/modules/user';

const { proxy }: any = getCurrentInstance();
const router = useRouter();
const { query } = useRoute();

const state = reactive({
  showType: 'ADD', // enum 'ADD' 'VIEW' 'AUDIT' 'UPDATE'
  status: null
});
state.showType = query.showType as string;

const accessToken = useUserStoreWithOut().getToken;

const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};
// 基础信息
const baseQuestions = reactive(indexService.getQuestions());
const baseAddConfig: any = {
  queryUrl: ['ADD'].includes(state.showType) ? Api.archivesRenewInfoAutoProductFormInfo : archivesBorrowApi.archivesBorrowGet,
  protType: ['ADD'].includes(state.showType) ? 'post' : 'get',
  urlName: ['ADD'].includes(state.showType) ? '' : query.id,
  noGetDataParams: true,
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true,
  beforeWithMethod: (data) => {
    state.status = data.status;
    return data;
  }
};

const numberRep = (value: string | number) => {
  if (typeof value === 'string') {
    return Math.floor(Number(value));
  } else if (typeof value === 'number') {
    return Math.floor(value);
  } else {
    return '';
  }
};

// 续借档案列表
// 申请
const renewalListAddQuestions = reactive(indexService.getRenewalListAddQuestions());
const renewalListAddConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
// 详情
const renewalListViewTable = reactive(indexService.getRenewalListViewQuestions());
const renewalListViewTableConfig: any = {
  queryUrl: Api.archivesRenewInfoRenewFilesPage,
  protType: 'post',
  params: { id: query.id },
  scroll: { x: '2000px' }
};

// 审批意见
const approvalOpinionsQuestions = reactive(indexService.getApprovalOpinionsQuestions());
const approvalOpinionsConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};

const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item) => {
    if (item.key === 'CUSTOMSELECTSERVE') {
      for (let i of renewalListAllData.value) {
        if (item.value.data.key === i.borrowInfoId) {
          for (let j in i) {
            for (let k in renewalListAddQuestions[0].value[item.value.index]) {
              // 文件名称处理
              if (k === 'name') {
                renewalListAddQuestions[0].value[item.value.index]['name'] = i.filename;
              }

              if (k === j) {
                renewalListAddQuestions[0].value[item.value.index][k] = i[j];
                renewalListAddQuestions[0].value[item.value.index].id = i.borrowInfoId; // 文件id

                // 原计划时间显示格式调整
                if (k === 'planReturnTime') {
                  renewalListAddQuestions[0].value[item.value.index]['planReturnTime'] = dayjs(i[j]).format('YYYY-MM-DD HH:mm:ss');
                }
              }
            }
          }
        }
      }
    } else if (item.key === 'CUSTOMEVENTSERVE') {
      // 计划归还时间调整
      const planReturnTime = renewalListAddQuestions[0].value[item.value.index]['planReturnTime'];
      if (!planReturnTime) return;
      renewalListAddQuestions[0].value[item.value.index]['renewReturnTime'] = dayjs(planReturnTime).add(item.value.value, 'day').format('YYYY-MM-DD HH:mm:ss');
    }
  });

const subscribePubSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item) => {
    if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '预览') {
      advancedQueryPreview({ id: item.value.data.fileListList.id, needRecord: false }).then((res) => {
        if (res && res.success) {
          window.open(res.data);
        }
      });
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '下载') {
      const url = `${searchManageApi.advancedQueryDownload}/${item.value.data.fileListList.id}`;
      downloadFile(url);
    }
  });

onMounted(() => {
  if (['ADD', 'UPDATE'].includes(state.showType)) {
    getFindBorrowFileByFileName();
  }

  if (['ADD'].includes(state.showType)) {
    getFileList();
  }

  if (['UPDATE'].includes(state.showType)) {
    renewFilesPageOpt();
  }
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
});

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
  subscribePubSub && subscribePubSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});

const renewalListAllData = ref<Array<any>>(null);

// 归还档案列表获取文件名称
const getFindBorrowFileByFileName = () => {
  archivesBorrowFindBorrowFileByFileName({ keyWord: '', isRenew: true }).then((res) => {
    let arr = [];
    for (let i of res.data) {
      arr.push({ label: i.filename, value: i.borrowInfoId, key: i.borrowInfoId });
    }

    // 归还档案列表（申请）
    if (['ADD', 'UPDATE'].includes(state.showType)) {
      renewalListAddQuestions[0].state.columns[2].options = [...arr];
    }

    renewalListAllData.value = [...res.data];
  });
};

// 续借档案列表
const renewFilesPageOpt = () => {
  archivesRenewInfoRenewFilesPage({ id: query.id }).then((res) => {
    if (res && res.success) {
      let arr = [];
      for (let i of res.data) {
        let obj = { ...i };
        delete obj['fileListList'];
        obj = Object.assign(obj, i.fileListList);
        arr.push(obj);
      }

      // 不从待归还列表来
      if (query.location !== 'toReturned') {
        renewalListAddQuestions[0].value = [...arr];
      }
    }
  });
};

// 获取续借档案列表
const getFileList = () => {
  archivesBorrowFindFileListByBorrowInfoIds({ borrowInfoIds: JSON.parse(window.sessionStorage.getItem('ids')) }).then((res) => {
    if (res && res.success) {
      // 从得归还列表来
      if (query.location === 'toReturned') {
        for (let i of res.data) {
          i.name = i.filename; // 文件名称处理
        }
        renewalListAddQuestions[0].value = [...res.data];
      }
    }
  });
};

const base = ref(null);
const renewalList = ref(null);

// 保存
const savePageInfo = (op) => {
  Modal.confirm({
    title: `是否确定${op === 0 ? '暂存' : '提交'}`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      let beforeSaveData = {
        baseData: {},
        borrowListData: []
      };
      // 提交时列表为空
      if (!renewalList.value.getDataFrom()?.customTable?.length && state.showType === 'ADD') {
        message.warn('错误，数据为空');
        return;
      }
      // 列表中相同文件
      const arr = renewalList.value.getDataFrom()?.customTable;
      const set = new Set();
      for (let i = 0; i < arr.length; i++) {
        const filesBoxCode = arr[i].filesBoxCode;
        if (set.has(filesBoxCode)) {
          message.warn(`错误, 档案编码${filesBoxCode}在续借列表中有重复项`);
          return;
        }
        set.add(filesBoxCode);
      }
      base.value.onFinish(({ billCode, creator, creatorName, department, departmentName, expirationReminder, createdTime }) => {
        beforeSaveData.baseData = Object.assign({}, { billCode, creator, creatorName, department, departmentName, expirationReminder, createdTime });
      });
      renewalList.value.onFinish((data) => {
        for (let { borrowType, borrowInfoId, name, code, fileCode, filesBoxCode, filesType, secretLevel, borrowCode, planReturnTime, renewDuration, renewReturnTime, id } of data.customTable) {
          let fileList = {};
          fileList['fileListList'] = { name, code, fileCode, filesType, secretLevel, filesBoxCode };

          // 时间保存格式调整
          planReturnTime = planReturnTime && dayjs(planReturnTime).format('YYYY-MM-DD HH:mm:ss');
          renewReturnTime = renewReturnTime && dayjs(renewReturnTime).format('YYYY-MM-DD HH:mm:ss');

          fileList = Object.assign(fileList, { borrowType, borrowCode, planReturnTime, renewReturnTime, renewDuration });

          if (['ADD', 'UPDATE'].includes(state.showType)) {
            if (typeof borrowInfoId !== 'undefined') {
              fileList['borrowInfoId'] = borrowInfoId;
            } else {
              fileList['borrowInfoId'] = id;
            }
          }

          beforeSaveData.borrowListData.push(fileList);
        }
      }, op == 0);
      const time = setTimeout(() => {
        if (op == 0 || (Object.keys(beforeSaveData.baseData).length > 0 && beforeSaveData.borrowListData.length)) {
          let finalSaveData = { ...beforeSaveData.baseData, fileList: [...beforeSaveData.borrowListData] };

          archivesRenewInfoSave({ ...finalSaveData, op: op, id: ['UPDATE'].includes(state.showType) ? query.id : null }).then((res) => {
            if (res && res.success) {
              message.success(res.message);
              goBack();
            }
          });
        }
        clearTimeout(time);
      }, 1000);
    }
  });
};

const approvalOpinions = ref(null); // 审批意见

// 审核
const reviewSubmit = () => {
  approvalOpinions.value.onFinish((data) => {
    let { id, applyResult, remark } = data;

    archivesRenewInfoAudit({ billId: id, applyResult, remark }).then((res) => {
      if (res && res.success) {
        message.success(res.message);
        goBack();
      }
    });
  });
};

const toUpdate = () => {
  router
    .replace({
      name: 'ArchivesManageAddRenew',
      query: {
        id: query.id,
        showType: 'UPDATE'
      }
    })
    .then(() => {
      router.go(0);
    });
};

const goBack = () => {
  router.go(-1);
};

// 下载文件
const downloadFile = (url) => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `${HOST}${url}`, true);
  xhr.setRequestHeader('token', accessToken);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (this.status == 200) {
      const blob = new Blob([this.response], { type: 'contentType' });
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
      filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
      const a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };
  xhr.send();
};
</script>
<style lang="less" scoped>
:deep(.ant-table-row) {
  .ant-form-item {
    margin-bottom: 0;
  }
}
</style>
